package com.joven.shelltest.utils.disruptor;

import com.lmax.disruptor.BlockingWaitStrategy;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.ProducerType;

import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

/**
 * @Author wzj
 * @Date 2023-08-15 10:47
 **/
public class DisruptorUtil {

    static Disruptor<SecondKillEvent> disruptor;

    static{
        SecondKillEventFactory factory = new SecondKillEventFactory();
        int ringBufferSize = 1024;
        ThreadFactory threadFactory = Thread::new;
        disruptor = new Disruptor<>(factory, ringBufferSize, (Executor) threadFactory);
        disruptor.handleEventsWith(new SecondKillEventConsumer());
        disruptor.start();

        //定义用于事件处理的线程池， Disruptor通过java.util.concurrent.ExecutorSerivce提供的线程来触发consumer的事件处理
//        ExecutorService executor = Executors.newFixedThreadPool(2);
//        //单线程模式，获取额外的性能
//        disruptor = new Disruptor<>(factory, ringBufferSize, executor,
//                ProducerType.SINGLE, new BlockingWaitStrategy());
    }

    public static void producer(SecondKillEvent kill){
        //获得ringBuffer环，用于接取生产者生产的事件
        RingBuffer<SecondKillEvent> ringBuffer = disruptor.getRingBuffer();
        SecondKillEventProducer producer = new SecondKillEventProducer(ringBuffer);
        producer.secondKill(kill.getSecKillId(),kill.getUserId());
    }
}
